package com.lanyam.travel.base.config;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.lanyam.travel.base.entity.base.MiniSessionManager;
import com.lanyam.travel.base.entity.base.MyShiroRealm;
import com.lanyam.travel.base.entity.base.PhoneLoginRealm;
import com.lanyam.travel.base.entity.base.WxLoginRealm;

@Configuration
public class ShiroConfig {
	// 将自己的验证方式加入容器
    @Bean
    public MyShiroRealm myShiroRealm() 
    {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        return myShiroRealm;
    }
    
    @Bean
    public WxLoginRealm wxLoginRealm()
    {
    	WxLoginRealm wxLoginRealm = new WxLoginRealm();
    	return wxLoginRealm;
    }
    
    @Bean
    public PhoneLoginRealm phoneLoginRealm()
    {
    	PhoneLoginRealm phoneLoginRealm = new PhoneLoginRealm();
    	return phoneLoginRealm;
    }
    
    @Bean
	public DefaultWebSessionManager sessionManager() {
    	MiniSessionManager  sessionManager = new MiniSessionManager();
//    	 Collection<SessionListener> listeners = new ArrayList<>();
//         listeners.add(new ShiroSessionListener());
//         sessionManager.setSessionListeners(listeners);
//         sessionManager.setSessionDAO(redisSessionDAO());
		sessionManager.setGlobalSessionTimeout(14400000);//4小时
		sessionManager.setSessionValidationSchedulerEnabled(true);
		sessionManager.setSessionIdUrlRewritingEnabled(false);
		return sessionManager;
	}
    
    // 权限管理，配置主要是Realm的管理认证
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//        securityManager.setRealm(myShiroRealm());
      //新增部分多realm配置  前端后台不同得验证   @chenkang
        ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();
        //至少成功一个都算认证通过得
        modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        securityManager.setAuthenticator(modularRealmAuthenticator);
        List<Realm> realms = new ArrayList<>();
        realms.add(myShiroRealm());
        realms.add(wxLoginRealm());
        realms.add(phoneLoginRealm());
        securityManager.setRealms(realms);
        //新增部分多realm配置  前端后台不同得验证
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }

    // Filter工厂，设置对应的过滤条件和跳转条件
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //配置拦截链 使用LinkedHashMap,因为LinkedHashMap是有序的，shiro会根据添加的顺序进行拦截
        // Map<K,V> K指的是拦截的url V值的是该url是否拦截
        Map<String, String> filterMap = new LinkedHashMap<String, String>();
        // //配置退出过滤器logout，由shiro实现
        filterMap.put("/logout", "logout");
        filterMap.put("/scenic/**", "anon");
        filterMap.put("/img/**", "anon");//保存图片的静态文件夹
        filterMap.put("/login/**", "anon");
        filterMap.put("/home/**", "anon");
        filterMap.put("/test/**", "anon");
        filterMap.put("/travelOrder/exportExcel", "anon");
        filterMap.put("/travelOrder/exportHotel", "anon");
        filterMap.put("/travelOrder/exportTicket", "anon");
        filterMap.put("/travelOrder/exportLine", "anon");

        filterMap.put("/upload/**", "anon");
        filterMap.put("/panicBuy/getAllPanicBuy","anon");
        filterMap.put("/date/getRemaidGoodFromNow","anon");
        filterMap.put("/date/getGoodsInfoBetweenDate","anon");
        filterMap.put("/order/createOrder","anon");
        filterMap.put("/order/wxpay","anon");
        filterMap.put("/order/wxNotify","anon");
        filterMap.put("/goodsInfo/getGoodsListByProductId","anon");
        filterMap.put("/ticket/getTickeTypeByProductId","anon");
        filterMap.put("/line/getTravelLineInfo","anon");
        filterMap.put("/panicBuy/getPanicBuyById","anon");
        filterMap.put("/order/queryOrderPageByUserId","anon");
        filterMap.put("/order/getOrderById","anon");
        filterMap.put("/order/paySuccess","anon");
        filterMap.put("/order/deleteOrder","anon");
        filterMap.put("/orderRefund/requireRefund","anon");
        filterMap.put("/distrTeam/getTeamMembers","anon");
        filterMap.put("/distrRecord/getDistrRecordByTeamId","anon");
        filterMap.put("/distrRecord/query","anon");
        filterMap.put("/caseWithdra/query","anon");
        filterMap.put("/cashRecord/query","anon");
        filterMap.put("/cashRecord/cashWithDraw","anon");
        filterMap.put("/distrUser/getDistrUserInfo","anon");
        filterMap.put("/distrUser/applyDistr","anon");

//        filterMap.put("/**", "anon");
        //authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问,先配置anon再配置authc。
        // 对所有用户认证
        filterMap.put("/**", "authc");
        // 错误页面，认证不通过跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
        // 登录，如果没有获取到登陆用户信息，会自动进入这个登陆接口。如果没有这个，会报Request method 'GET' not supported异常
        shiroFilterFactoryBean.setLoginUrl("login");
        // 首页
        shiroFilterFactoryBean.setSuccessUrl("/index");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }
    
    // 加入注解的使用，不加入这个注解不生效
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
    
    /**
     * 处理未授权的异常，返回自定义的错误页面（403）,上面配置过，这里不需要
     * @return
     */
//    @Bean
//    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
//        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
//        Properties properties = new Properties();
//        /*未授权处理页*/
//        properties.setProperty("UnauthorizedException", "403.html");
//        resolver.setExceptionMappings(properties);
//        return resolver;
//    }
}
